package conf

import (
	"encoding/xml"
	"github.com/farmerx/gorsa"
	"io/ioutil"
	_ "strings"

	"World/common/logger"
)

var (
	EncryptCfg *EncryptConf
)

const (
	rsaPubkey = `-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA0KFDLlzBfWPIJLTT806Q
KpjfVdkNHJoErZO+9MLHGC/Ye/9KG9WzDcXEY+2aEk7CInpPGwNmBoGOMCyUmMvc
FH0dYhxsfaBHnyrIFu097zXeZ3MzAw7DKpY09zQgG3ZBKxmaAz1b6xrGmQpNIB3A
zBBQrJUEbA7EsGUXPHSsSQ7JoQgFjcAuDb6ChJNdl74JNwXwekOxvgHMPGA7T2kN
NJg71xITtPXAbVYgkltDhNn4b5C5qlrQkBehb9Ky8KVlI6W6t6wDcFghiivj7FDH
gjRYBI0rE+6q023ofKo5EPaz9iENphjYRzqw790JK2LedUpETIJhqQq2qnJm+FrE
1wIDAQAB
-----END PUBLIC KEY-----`
	rsaPrikey = `-----BEGIN PRIVATE KEY-----
MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDQoUMuXMF9Y8gk
tNPzTpAqmN9V2Q0cmgStk770wscYL9h7/0ob1bMNxcRj7ZoSTsIiek8bA2YGgY4w
LJSYy9wUfR1iHGx9oEefKsgW7T3vNd5nczMDDsMqljT3NCAbdkErGZoDPVvrGsaZ
Ck0gHcDMEFCslQRsDsSwZRc8dKxJDsmhCAWNwC4NvoKEk12Xvgk3BfB6Q7G+Acw8
YDtPaQ00mDvXEhO09cBtViCSW0OE2fhvkLmqWtCQF6Fv0rLwpWUjpbq3rANwWCGK
K+PsUMeCNFgEjSsT7qrTbeh8qjkQ9rP2IQ2mGNhHOrDv3QkrYt51SkRMgmGpCraq
cmb4WsTXAgMBAAECggEBAKnec+Xe7khbI04H0f9sO2QDnuy2Ur+0BBUUlEmUAimG
Y3zqqvuo7yZKnZJDlsxLRjRuY9R52ut3Nz+wPL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vI+hQ2J/0OkDQgfpVctjhQXxhsVwy34oFqokc+3GYIU7B3sEQ5EsMa7Jh5L6
3PCk5re/urFJs7fBbq7tmNY=
-----END PRIVATE KEY-----`
	aesKey = "SwGqJKkUgpDfKza5"
	aesIv  = "8u8LP27JDTXtX2Wl"
)

type MysqlConf struct {
	Ip           string `xml:",attr"`
	Port         int    `xml:",attr"`
	User         string `xml:",attr"`
	Pwd          string `xml:",attr"`
	Database     string `xml:",attr"`
	LoadInterval int    `xml:",attr"`
}

type ListenAddr struct {
	Host       string `xml:",attr"`
	Test       int    `xml:",attr"`
	SourceType uint32 `xml:",attr"`
}

type ListenRpcAddr struct {
	Host string `xml:",attr"`
}

type ZooKeeper struct {
	Host string `xml:",attr"`
}

type ClientVersion struct {
	Lastest string `xml:",attr"`
}

type Alliance struct {
	ClubNumMax int `xml:",attr"`
}

type Jackpot struct {
	Award2ClubPercent int `xml:",attr"`
}
type EncryptConf struct {
	Prikey string
	Pubkey string
	AesKey []byte
	AesIv  []byte
}

type TexasConf struct {
	GameDB MysqlConf `xml:"GameDB"`
	//	ActiveDB                MysqlConf           `xml:"ActiveDB"`
	ListenAddrConf          ListenAddr          `xml:"ListenAddr"`
	ListenRpcAddrConf       ListenRpcAddr       `xml:"ListenRpcAddr"`
	ZooKeeperConf           ZooKeeper           `xml:"ZooKeeper"`
	VersionConf             ClientVersion       `xml:"ClientVersion"`
	BlindConf               Blinds              `xml:"Blinds"`
	HandlevelConf           Handlevels          `xml:"Handlevels"`
	AllianceConf            Alliance            `xml:"Alliance"`
	JackpotConf             Jackpot             `xml:"Jackpot"`
	EventReportHttpAddrConf EventReportHttpAddr `xml:"EventReportHttpAddr"`
	Redis                   RedisConf           `xml:"Redis"`
	Php                     PhpConf             `xml:"Php"`
}

type Blinds struct {
	XMLName   xml.Name `xml:"Blinds"`
	BlindList []Blind  `xml:"Blind"`
}

type Blind struct {
	XMLName     xml.Name `xml:"Blind"`
	ID          int      `xml:",attr"`
	Scale       int      `xml:",attr"`
	DrawinAmout int      `xml:",attr"`
}

type RedisConf struct {
	Host     string `xml:",attr"`
	Db       uint32 `xml:",attr"`
	Password string `xml:",attr"`
}

type Handlevels struct {
	XMLName       xml.Name    `xml:"Handlevels"`
	HandlevelList []Handlevel `xml:"Handlevel"`
}

type Handlevel struct {
	XMLName      xml.Name `xml:"Handlevel"`
	ID           int      `xml:",attr"`
	AwardPercent int      `xml:",attr"`
}
type EventReportHttpAddr struct {
	Host          string `xml:",attr"`
	CurrencyUri   string `xml:",attr"`
	EventUri      string `xml:",attr"`
	FairPlayUri   string `xml:",attr"`
	DeviceInfoUri string `xml:",attr"`
}

type PhpConf struct {
	Addr string `xml:",attr"`
}

var (
	config = new(TexasConf)
)

func GetGameDBConf() MysqlConf {
	return config.GameDB
}

/*
func GetActiveDBConf() MysqlConf {
	return config.ActiveDB
}
*/
func GetSourceType() uint32 {
	return config.ListenAddrConf.SourceType
}
func GetSocketListenAddr() string {
	return config.ListenAddrConf.Host
}

func GetRpcListenAddr() string {
	return config.ListenRpcAddrConf.Host
}

func GetRedisConf() RedisConf {
	return config.Redis
}
func GetEventReportHttpAddrConf() EventReportHttpAddr {
	return config.EventReportHttpAddrConf
}

func GetLastestVersion() string {
	return config.VersionConf.Lastest
}

func GetAllianceClubNumMax() int {
	return config.AllianceConf.ClubNumMax
}

func GetAward2ClubPercent() int {
	return config.JackpotConf.Award2ClubPercent
}

func GetPhpConf() PhpConf {
	return config.Php
}

func LoadConf(filename string) error {
	content, err := ioutil.ReadFile(filename)
	if err != nil {
		logger.Notic("read file:%v error:", filename, err)
		return err
	}
	logger.Info("conf xml:%v", string(content))
	err = xml.Unmarshal(content, config)
	if err != nil {
		logger.Notic("decode xml error:%v", err)
		return err
	}
	DumpConf()
	return nil
}

//设置加密秘钥
func SetEncryptKey() error {
	var err error
	EncryptCfg = &EncryptConf{
		Pubkey: rsaPubkey,
		Prikey: rsaPrikey,
		AesKey: []byte(aesKey),
		AesIv:  []byte(aesIv),
	}
	logger.Info("the EncryptCfg:%+v", EncryptCfg)
	if err = gorsa.RSA.SetPublicKey(EncryptCfg.Pubkey); err != nil {
		logger.Info("set rsa public key err:%v", err)
		return err
	}
	if err = gorsa.RSA.SetPrivateKey(EncryptCfg.Prikey); err != nil {
		logger.Info("set rsa private key err:%v", err)
		return err
	}
	return nil
}

func DumpConf() {
	logger.Info("--------------config dump----start--------")
	logger.Info("Player Mysql ip:%v port: %V user:%v pwd:%v database:%v", config.GameDB.Ip, config.GameDB.Port, config.GameDB.User, config.GameDB.Pwd, config.GameDB.Database)
	logger.Info("ListenAddr:%v", config.ListenAddrConf.Host)
	logger.Info("VersionConfg:%v", config.VersionConf.Lastest)
	logger.Info("Blinds:%+v", config.BlindConf)
	logger.Info("config.BlindConf:%+v", config.BlindConf)
	logger.Info("config.HandlevelConf:%+v", config.HandlevelConf)
	logger.Info("ListenRpcAddrConf:%+v", config.ListenRpcAddrConf)
	logger.Info("--------------config dump----end--------")
}

func GetBlindConf() Blinds {
	return config.BlindConf
}

func GetBlindByIndex(idx uint32) Blind {
	for _, value := range config.BlindConf.BlindList {
		if value.ID == int(idx) {
			return value
		}
	}
	return config.BlindConf.BlindList[0]
}

func GetHandlevelByIndex(idx uint32) Handlevel {
	for _, value := range config.HandlevelConf.HandlevelList {
		if value.ID == int(idx) {
			return value
		}
	}
	return config.HandlevelConf.HandlevelList[0]
}

func GetHandlevels() []Handlevel {
	return config.HandlevelConf.HandlevelList
}

func IsTest() bool {
	return false
	if config.ListenAddrConf.Test == 1 {
		return true
	}
	return false
}
